/**
 * 用户管理页面js
 * 版权所有：上海戈品投资管理有限公司
 *   author king
     功能说明：用户管理
     创建日期：2015-10-15
     修改记录：
     备注说明：
 */

$(document).ready(function() {
	showCommandAgent();
	queryAdProList();
});


/**
 * 用户列表
 * @returns
 */
var showCommandAgent = function(){
	var agentId = $('#agentId').val(); //代理人编号
	var agentName = $('#agentName').val(); //代理人名称
	var userName=$("#userName").val();
	var userId=$("#userId").val();
	var toBlackType=$("#isBlackType").val();
	var userType=$("#userType").val();//用户类型
	var courRealName=$("#courRealName").val();
	var courTel=$("#courTel").val();
	var createTime = $("#createTime").val();//关注时间
	var userStatus=$("#userStatus").val();//用户状态
	var cancelFocusTime=$("#cancelFocusTime").val();//取关时间
	var inviteUser=$("#inviteUser").val();
	
	var datas =  {"p":"seachAgentDevelopUsers","m":"query","agentId":agentId,"agentName":agentName,"userName":userName,"userId":userId,"toBlackType":toBlackType,"userType":userType,"courRealName":courRealName,"courTel":courTel,"createTime":createTime,"userStatus":userStatus,"cancelFocusTime":cancelFocusTime,"inviteUser":inviteUser};
	var columnDefine = {"id":"用户ID","name":"用户昵称","phone":"手机","registTime":"关注时间","agentId":"代理人编号","agentName":"代理人名称","isBlack":"是否拉黑"};
	
	var formatters={
	            "registTime": function (column, rowData)
	            {
    				var newTime= new Date(rowData.registTime);
    				var rowText=newTime.getFullYear()+'-'+getTheSureTime((newTime.getMonth()+1))+'-'
    				+getTheSureTime(newTime.getDate())+' '+getTheSureTime(newTime.getHours())+':'
    				+getTheSureTime(newTime.getMinutes())+':'+getTheSureTime(newTime.getSeconds());
    				return rowText;
	            },
	            "isBlack": function (column, rowData)
	            {
	            	var is_black='';
    				switch(rowData.isBlack){
    					case 1:
    						is_black='白名单用户';
    						break;
    					case 2:
    						is_black='被拉黑用户';
    						break;
    					case 0:
    						is_black='其他用户';
    						break;
    					default:
    						
    				}
	            	return is_black;
	            },
	            "invite": function (column, rowData)
	            {
    				if(rowData.invite>0){
    					return "推广用户("+rowData.invite+")";
    				}else{
    					return "";
    				}
	            }
	 };
	 var buttons =''; //操作按钮
		buttons+='<p>';
		buttons+='</p>';
	   hui.pager('service',datas ,"dataList", columnDefine , formatters , buttons ); //分页查询
	
};

function getTheSureTime(emp){
	return emp>9?emp:"0"+emp;
}

/**
 * 查看用户
 * @returns
 */
var showDevelopUser = function(){
	var data = $('#pop_win .data').text();
	var json = eval('('+data+')');
	window.location.href='page?p=page/showAgentDevelop&agentId='+json.id ;
};

/**
 * 打开发送微信消息窗口
 * @returns
 */
var showWechatMsgWin = function(){
	$('#sendWechatWin input').val('');
	$('#sendWechatWin textarea').val('');
	$('#sendWechatWin').modal('show');
};

/**
 * 打开发送图文消息窗口
 * @returns
 */
var showWechatPicMsgWin = function(){
	
	$('#sendWechatPicWin input').val('');
	$('#sendWechatWin').modal('show');
};


/**
 * 发送微信消息
 * @returns
 */
var sendMsg = function(){
	
	var sendMsgType = $('#sendWechatWin .sendMsgType').val();
	var msgTemplate = $('#sendWechatWin .msgTemplate').val();
	var wxMessage = $('#sendWechatWin .wxMessage').val();
	
	return;
	
	var datas = {"p":"agentManageOperate","m":"edit","id":agentId,"name":agentName,"phone":agentTel,"address":agentAddress,"type":1};

	var json = common.ajaxRequest('service', datas, 'POST');
	if( json && json.result == 0 )
	{
		agentList();
		$('#modifyAgentWin').modal('hide');
		common.showMsg('info', '', '修改成功!');
	}
	else
	{
		common.showMsg('error', '', json.message);
	}	
};

/**
 *  图文消息
 * @returns
 */
var sendPicMsg = function(){
	
	var agentName = $('#newAgentWin .agentName').val();
	var agentTel = $('#newAgentWin .tel').val();
	var agentAddress = $('#newAgentWin .address').val();
	var datas = {"p":"agentManageOperate","m":"add","name":agentName,"phone":agentTel,"address":agentAddress,"type":1};

	return;
	
	var json = common.ajaxRequest('service', datas, 'POST');
	if( json && json.result == 0 )
	{
		agentList();
		$('#newAgentWin').modal('hide');
		common.showMsg('info', '', '新建成功!');
	}
	else
	{
		common.showMsg('error', '', json.message);
	}	
	
};

/**
 * 打开窗口
 * @returns
 */
var showWin = function(id){
	$('#'+id).modal('show');
};

/**
 * 设置推广权限，显示窗口
 * @returns
 */
var sheZhiTGQX=function(){
	var userIds=getCheckedIds("dataList");
	if(!userIds){
		return;
	}
	showWin("showWinOfSure");
	var html="<span>设置扫描次数：</span><input type='text' id='scanNum' /><br><br>";
	html+="<div>您将为一下用户设置推广权限：用户ID("+getCheckedIds("dataList")+")</div>";
	$("#winOfSureText").html(html);
	$("#winOfSure").attr("onclick","sheZhiTGQXRequet()");
};
/**
 * 设置推广权限，ajax请求
 * @returns
 */
var sheZhiTGQXRequet=function(){
	var userIDS=getCheckedIds("dataList");
	if(!userIDS){
		return;
	}
	var scanNum=$("#scanNum").val();
	if(!/^\d+$/.test(scanNum)){
		common.showMsg('error', '', "请输入数字");
		return;
	}
	var datas = {"p":"seachAgentDevelopUsers","m":"setUpPermissions","usersIds":userIDS,"scanNum":scanNum};

	var json = common.ajaxRequest('service', datas, 'POST');
	if( json && json.result == 0 )
	{
		showCommandAgent();
		$('#showWinOfSure').modal('hide');
		$('#setupWin').modal('hide');
		common.showMsg('info', '', '设置成功!');
	}
	else
	{
		common.showMsg('error', '', json.message);
	}	
};

/**
 * 更改用户白名单
 * @returns
 */
var changeUserIsBlack=function(){
	var userIds=getCheckedIds("dataList");
	if(!userIds){
		return;
	}
	var isBlack=$("#setIsBlackType").val();
	if(isBlack=="-1"){
		common.showMsg('error', '', '请选择状态');
		return;
	}
	

	var datas = {"p":"seachAgentDevelopUsers","m":"changeUserIsBlack","usersIds":userIds,"setIsBlackType":isBlack};

	var json = common.ajaxRequest('service', datas, 'POST');
	if( json && json.result == 0 )
	{
		showCommandAgent();
		$('#setupWin').modal('hide');
		common.showMsg('info', '', '修改成功!');
	}
	else
	{
		common.showMsg('error', '', json.message);
	}	
};
var getCheckedIds=function(id){
	var idsDom=$("#"+id+" input[name='select']:checked");
	var adActiveIds="";
	if(idsDom.length<1){
		common.showMsg('error', '', '请至少选择一条记录');
		return false;
	}else if(idsDom.length==1){
		adActiveIds=idsDom.eq(0).val();
	}else{
		if(idsDom.eq(0).val()!="all"){
			adActiveIds+=idsDom.eq(0).val()+",";
		}
		for(var i=1;i<idsDom.length;i++){
			adActiveIds+=idsDom.eq(i).val()+",";
		}
		adActiveIds=adActiveIds.substring(0, adActiveIds.length-1);
	}
	return adActiveIds;
};
/**
 * 手动发红包弹窗
 * @returns
 */
var systemSendRedPack=function(){
	var ids=getCheckedIds("dataList");
	if(!ids){
		return;
	}
	var html='<select class="form-control m-b "  id="projectNo" style="width:200px;"><option value="">请选择项目</option>'+$("#adProjects").html()+'</select>';
	html+='<div>您将给以下用户发送红包：用户ID('+ids+')</div>';
	$("#winOfSureText").html(html);
	$("#winOfSure").attr("onclick","sSendRedPackRequest()");
	showWin("showWinOfSure");
	$("#setupWin").modal("hide");
	
};
/**
 * 手动发红包请求
 * @returns
 */
var sSendRedPackRequest=function(){
	var userIds=getCheckedIds("dataList");
	if(!userIds){
		return;
	}
	var projectNo=$("#projectNo").val();
	if(projectNo==""){
		common.showMsg('error', '', "请选择项目");
		return;
	}
	var datas = {"p":"adActiveManage","m":"adminSendRedPack","userIds":userIds,"projectNo":projectNo};
	var json = common.ajaxRequest('service', datas, 'POST');
	if( json && json.result == 0 )
	{
		var sendResults=json.sendResult;
		sendRedPackReponse(userIds,sendResults);
		showCommandAgent();
		
	}
	else
	{
		common.showMsg('error', '', json.message);
	}	
};
/**
 * 处理发红包请求后的结果
 */
var sendRedPackReponse=function(adActiveIds,sendResult){
	var results=sendResult.split("||");
	var ids=adActiveIds.split(",");
	var rs="";
	var adR;
	for(var i=0;i<results.length-1;i++){
		adR=results[i].split("_");
		rs+="<p style='color:#FFFFFF;background-color:"+levalInfo(adR[0])+"'>userID="+ids[i]+"	的红包发放情况是："+adR[1]+"</p>";
	}
	var noRs="<br><p>以下的项目还没有发送红包，请您继续操作：</p>";
	var flag=false;
	for(var j=results.length-1;j<ids.length;j++){
		noRs+="<p style='color:#FFFFFF;background-color:"+levalInfo(adR[0])+"'>没有发红包的项目编号：	"+ids[j]+"</p>";
		flag=true;
	}
	if(flag){
		rs+=noRs;
	}
	$("#winOfSureText").html(rs);
	$("#winOfCancell").html("确定").prev().remove();
	$("#showWinOfSure").modal("show");
};
/**
 * 发红包返回结果，等级判断
 * @param e
 * @returns
 */
var levalInfo=function(e){
	var color='';
	switch(e){
		case "0"://成功
			color="#18A689";
			break;
		case "1"://不能发红包
			color="#F7A54A";
			break;
		case "2"://发红包失败
			color="#EC4758";
			break;
		case "3"://发红包异常（微信红包接口调用成功）
			color="#BF0000";
			break;
		default :
			color="#FFFFFF";
	}
	return color;
};
/**
 * 查询可用的广告项目
 * @returns
 */
var queryAdProList=function(){
	//http://osc.kuaiyoukuaidi.com/service?p=merchantManage&m=redpackSummary
	var datas = {"p":"merchantManage","m":"queryAdProList"};
	var json = common.ajaxRequest('service', datas, 'POST');
	if( json && json.result == 0 )
	{
		var adList=json.adProjects;
		var str="";
		$(adList).each(function(){
			str+='<option value="'+this.projectNo+'" money="'+this.operatorMoney+'">'+this.wx_name+'</option>';
		});
		$("#adProjects").html(str);
	}
	else
	{
		common.showMsg('error', '', json.message);
	}	
	
};
var choosePro=function(obj){
	var money=$(obj).attr("money");
	if(money!=""){
		$(obj).next().append("<br><br>红包金额："+$(obj).val()+"元");
	}else{
		$(obj).next().append("<br><br>红包金额：--元");
	}
};